package cn.b.sky.mes.hr.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.b.sky.mes.hr.model.Performance;
import cn.b.sky.mes.hr.model.PersonnelConfirm;
import cn.b.sky.mes.hr.model.ShiftingPermission;
import cn.b.sky.mes.hr.model.condition.PersonnelConfirmCondition;
import cn.b.sky.mes.hr.service.PersonnelConfirmService;
import cn.b.sky.mes.hr.service.PersonnelService;
import cn.b.sky.mes.hr.service.ShiftingPermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.mes.cm.service.WorkCenterService;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.enums.DwzCallbackType;
import cn.b.sky.common.exception.ImeException;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.common.utils.DateUtils;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;

/**
 * 
 * <strong>Title : PersonnelConfirmController.java<br></strong>
 * <strong>Package : cn.b.sky.mes.hr.controller<br></strong>
 * <strong>Description : </strong>报工控制器<br> 
 * <strong>Create on : 2016-4-20 下午5:22:39<br></strong>
 * <p>
 * @author JinQuan.Fu<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping("/personnelConfirm/*")
public class PersonnelConfirmController extends SecurityController {

  @Resource
  private PersonnelConfirmService personnelConfirmService;

  @Resource
  private ShiftingPermissionService shiftingPermissionService;

  @Resource
  private WorkCenterService workCenterService;

  @Resource
  private PersonnelService personnelService;

  @RequestMapping("personnelConfirm_list")
  public String listpersonnelConfirm(@ModelAttribute("condition") PersonnelConfirmCondition condition, String navTabId,
                                     Model model) {
    condition.setSiteCode(this.getSiteCode());
    //获取当前用户的工作中心权限
    List<ShiftingPermission> workCenters = shiftingPermissionService.getPermissionsByUser(this.getSiteCode(),
        SecurityContextUtil.getCurrentUserName(), null);
    //没有工作中心权限则不过滤
    if (workCenters == null || workCenters.size() <= 0) {
      condition.setData(new ArrayList<Performance>());
      condition.setTotalCount(0);
      model.addAttribute("page", condition);
    } else {
      condition.setPermission(workCenters);
      List<PersonnelConfirm> list = personnelConfirmService.getPersonnelConfirmListByCondition(condition);
      int count = personnelConfirmService.getPerformanceCountByCondition(condition);
      condition.setData(list);
      condition.setTotalCount(count);
    }
    model.addAttribute("page", condition);
    model.addAttribute(NAVTABID, navTabId);
    return "hr/personnelConfirm/personnelConfirm_list";
  }

  @RequestMapping("personnelConfirm_add")
  public String addPersonnelConfirm(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    return "hr/personnelConfirm/personnelConfirm_add";
  }

  @RequestMapping("savePersonnelConfirm")
  @ResponseBody
  public DWZResult savePersonnelConfirm(PersonnelConfirm personnelConfirm, Model model, String navTabId) {
    personnelConfirm.setSiteCode(this.getSiteCode());
    this.setCreateInfo(personnelConfirm);
    if (personnelService.getPersonnelInfo(personnelConfirm.getSiteCode(), personnelConfirm.getPersonnelCode()).getLockFlag()==1) {
      return ajaxError(this.getImeViewMessageI18n(getCurrentLanguage(), "PersonnelLock.M"));
    }
    personnelConfirm.setWorkCentertext(workCenterService.getWorkCenterByPK(this.getSiteCode(),
        personnelConfirm.getWorkCenterCode()).getWorkCenterText());
    personnelConfirm.setShiftingWorkcenterText(workCenterService.getWorkCenterByPK(this.getSiteCode(),
        personnelConfirm.getShiftingWorkCenterCode()).getWorkCenterText());
    
    if (!this.checkPersonnelConfirmUser(personnelConfirm)) {
      return ajaxError(this.getImeViewMessageI18n(getCurrentLanguage(), "batchPersonnelConfirmError.M"));
    }
    personnelConfirmService.savePersonnelConfirm(personnelConfirm);
    return dialogAjaxDone(navTabId, null, null, personnelConfirm);
  }

  @RequestMapping("modifyPersonnelConfirm")
  public String modifyPersonnelConfirm(Long id, String navTabId, Model model) {
    if (id == null) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    PersonnelConfirm personnelConfirm = personnelConfirmService.getPersonnelConfirmById(id, this.getSiteCode());
    personnelConfirm.setWorkCentertext(workCenterService.getWorkCenterByPK(personnelConfirm.getSiteCode(),
        personnelConfirm.getWorkCenterCode()).getWorkCenterText());
    personnelConfirm.setPersonnelName(personnelService.getPersonnelInfo(personnelConfirm.getSiteCode(),
        personnelConfirm.getPersonnelCode()).getPersonnelName());
    model.addAttribute("personnelConfirm", personnelConfirm);
    model.addAttribute(NAVTABID, navTabId);
    return "hr/personnelConfirm/personnelConfirm_edit";
  }

  @RequestMapping("updatePersonnelConfirm")
  @ResponseBody
  public DWZResult updatePersonnelConfirm(PersonnelConfirm personnelConfirm, String navTabId, Model model) {
    personnelConfirm.setSiteCode(this.getSiteCode());
    this.setCreateInfo(personnelConfirm);
    personnelConfirm.setShiftingWorkCenterCode(personnelConfirm.getWorkCenterCode());
    if (!this.checkPersonnelConfirmUser(personnelConfirm)) {
      return ajaxError(this.getImeViewMessageI18n(getCurrentLanguage(), "batchPersonnelConfirmError.M"));
    }
    personnelConfirmService.updatePersonnelConfirm(personnelConfirm);
    return dialogAjaxDone(navTabId, null, null, null);
  }

  @RequestMapping("personnelConfirm_batchadd")
  public String batchaddPersonnelConfirm(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    return "hr/personnelConfirm/personnelConfirm_batchadd";
  }

  @RequestMapping("saveBatchPersonnelConfirm")
  @ResponseBody
  public DWZResult saveBatchPersonnelConfirm(PersonnelConfirm personnelConfirm, Model model, String navTabId,
      String personnel, HttpServletRequest request) {
    if (personnel.length() <= 0) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), SystemConstant.PARAMETERNULL));
    }
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>();
    int failures = 0;
    String message = "";
    String[] personnels = personnel.split(",");
    for (int i = 0; i < personnels.length; i++) {
      PersonnelConfirm p = new PersonnelConfirm();
      p.setSiteCode(this.getSiteCode());
      this.setCreateInfo(p);
      p.setPersonnelCode(personnels[i]);
      p.setShiftingWorkCenterCode(personnelService.getPersonnelInfo(p.getSiteCode(), p.getPersonnelCode())
          .getWorkCenterCode());
      p.setConfirmDatetime(personnelConfirm.getConfirmDatetime());
      p.setMaterialCode(personnelConfirm.getMaterialCode());
      p.setQuantity(personnelConfirm.getQuantity());
      p.setMemo(personnelConfirm.getMemo());
      if (!this.checkPersonnelConfirmUser(p)) {
        message += getImeViewMessageI18n(getCurrentLanguage(), "batchPersonnelConfirmError.M", p.getPersonnelCode(),
            DateUtils.getDateUtils().format(p.getConfirmDatetime()));
        reports.add(new BatchJobReport(p.getPersonnelCode(), message, false, this.getCurrentLanguage(), this.getSiteCode()));
        failures++;
        continue;
      }
      personnelConfirmService.savePersonnelConfirm(p);
    }
    if (failures == 0) {
      return dialogAjaxDone(navTabId, null, null, null);
    } else {
      return batchjobAjaxDone(request, DwzCallbackType.CLOSECURRENT, reports);
    }
  }

  @RequestMapping("viewPersonnelConfirm")
  public String viewPersonnelConfirm(Long id, String navTabId, Model model) {
    if (id == null) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    PersonnelConfirm personnelConfirm = personnelConfirmService.getPersonnelConfirmById(id, this.getSiteCode());
    personnelConfirm.setWorkCentertext(workCenterService.getWorkCenterByPK(personnelConfirm.getSiteCode(),
        personnelConfirm.getWorkCenterCode()).getWorkCenterText());
    personnelConfirm.setPersonnelName(personnelService.getPersonnelInfo(personnelConfirm.getSiteCode(),
        personnelConfirm.getPersonnelCode()).getPersonnelName());
    model.addAttribute("personnelConfirm", personnelConfirm);
    model.addAttribute(NAVTABID, navTabId);
    return "hr/personnelConfirm/personnelConfirm_view";
  }

  @RequestMapping("deletepersonnelConfirm")
  @ResponseBody
  public DWZResult deletePersonnelConfirm(String ids, String navTabId, Model model, HttpServletRequest request) {
    if (StringUtils.isBlank(ids)) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    String[] idArr = ids.split(",");
    for (int i = 0; i < idArr.length; i++) {
      personnelConfirmService.deletePersonnelConfirmById(Long.valueOf(idArr[i]));
    }
    return navTabAjaxDone(navTabId, null, null, null,
        getImeViewMessageI18n(this.getCurrentLanguage(), "successfulOperation.M"), null);
  }

  /** 
   * <strong>Title : checkPersonnelConfirmUser<br></strong>
   * <strong>Description : </strong>检查人员：同一时间、同一实际工作中心、同一物料是否报工<br> 
   * <strong>Create on : 2016-4-27 下午3:15:07<br></strong>
   * <p>
   * @param personnelConfirm
   * @return
   * boolean
   * @throws 
   * @author JinQuan.Fu<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  private boolean checkPersonnelConfirmUser(PersonnelConfirm personnelConfirm) {
    int count = personnelConfirmService.getPerformanceCountByCheck(personnelConfirm);
    if (count != 0) {
      return false;
    }
    return true;
  }
}
